"use strict";
import { useState, useEffect, useRef } from "react";

/*
 * 组件注释
 * create by wuqiong
 * creation time 2021/05/31
 * 表格的自定义hook
 * */

const Index = props => {
  const {
    dataInterface,
    implemented = true,
    isPagination = true,
    paths = ["data"],
    payload = {},
  } = props;
  const [rawData, setRawData] = useState({});
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(payload.pageNum || 1);
  const [pageSize, setPageSize] = useState(10);
  const [cachePayload, setCachePayload] = useState({ ...payload });
  const [loading, setLoading] = useState(dataInterface ? false : true);
  const dataRef = useRef();
  dataRef.current = { dataInterface, payload };

  const onChange = (page, pageSize) => {
    setPage(page);
    setPageSize(pageSize);
    if (isPagination) {
      getTableList(dataInterface, { page, pageSize, ...payload });
    }
  };

  const getTableList = (
    dataInterface,
    { page = 1, pageSize = 10, ...other }
  ) => {
    setLoading(true);
    if (!dataInterface || typeof dataInterface !== "function") {
      setLoading(false);
      return;
    }
    dataInterface({
      ...(isPagination ? { pageNum: page, pageSize } : {}),
      ...other,
    }).then(resp => {
      if (resp && resp.status === 1) {
        try {
          let data = JSON.parse(JSON.stringify(resp));
          let _path = [...paths];
          while (_path.length) {
            data = data[_path[0]];
            _path = _path.slice(1);
          }

          if (Array.isArray(data)) {
            setTotal(data.length);
            setDataSource(data || []);
          } else {
            setTotal(data.total);
            setDataSource(data.list ||[]);
          }
        } catch {
          setTotal(0);
          setDataSource([]);
        }
        setRawData(resp.data);
      }
      setPage(page);
      setPageSize(pageSize);
      setLoading(false);
    });
  };

  const resetTable = () => {
    setTotal(0);
    setPage(1);
    setPageSize(10);
    setDataSource([]);
  };

  const updataTable = params => {
    const {
      dataInterface = dataRef.current.dataInterface,
      payload = dataRef.current.payload,
    } = params || {};
    const page = payload?.page || 1;
    const pageSize = payload?.pageSize || 10;
    setPage(page);
    setPageSize(pageSize);
    setCachePayload({ ...payload });
    getTableList(dataInterface || props.dataInterface, {
      ...cachePayload,
      ...payload,
      page,
      pageSize,
    });
  };

  useEffect(() => {
    if (!!implemented) {
      resetTable();
      setCachePayload({ ...payload });
      getTableList(dataInterface, { ...payload });
    }
  }, [JSON.stringify(payload), dataInterface, implemented]);

  return {
    tableConfig: {
      loading: loading,
      dataSource: [...dataSource],
      pagination:
        isPagination && total >= pageSize
          ? {
              total: total,
              size: "default",
              current: page,
              pageSize: pageSize,
              onChange: onChange,
              onShowSizeChange: onChange,
              showQuickJumper: true,
              showSizeChanger: true,
              hideOnSinglePage: true,
              showTotal: total => `共 ${total} 条`,
            }
          : false,
      scroll: dataSource.length
        ? {
            scrollToFirstRowOnChange: true,
            x: "max-content",
          }
        : false,
    },
    page,
    pageSize,
    rawData,
    updataTable,
    resetTable,
  };
};
export default Index;
